package co.yixiang.utils;

import co.yixiang.domain.QiniuConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 上线使用
 */
public class TencentCOSUtils {
    //设置bucket的区域, COS地域的简称请参照
    //https://hpapp-1301523788.cos.ap-guangzhou.myqcloud.com，根据自己创建的存储桶选择地区
    private static ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));


    /**
     * 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口 大文件上传请参照 API 文档高级 API 上传
     * @param in
     * @param fileName
     * @param qiniuConfig
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public static String uploadfile(InputStream in, String fileName, QiniuConfig qiniuConfig) throws CosClientException, CosServiceException {
        // 1 初始化用户身份信息(secretId, secretKey，可在腾讯云后台中的API密钥管理中查看！
        COSCredentials cred = new BasicCOSCredentials(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        //存储桶名称
        String bucketName = qiniuConfig.getBucket();
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, in,null);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }
        return fileName;
    }


    /**
     * 下载文件
     */
    public static void downFile(QiniuConfig qiniuConfig) {
        // 1 初始化用户身份信息(secretId, secretKey，可在腾讯云后台中的API密钥管理中查看！
        COSCredentials cred = new BasicCOSCredentials(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        //要下载的文件路径和名称
        String key = "down/demo1.jpg";
        // 指定文件的存储路径
        File downFile = new File("src/test/resources/mydown.txt");
        //存储桶名称
        String bucketName = qiniuConfig.getBucket();
        // 指定要下载的文件所在的 bucket 和对象键
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        ObjectMetadata downObjectMeta = cosclient.getObject(getObjectRequest, downFile);
    }


    /**
     * 删除文件
     */
    public static void deletefile(String key, QiniuConfig qiniuConfig) throws CosClientException, CosServiceException {
        // 1 初始化用户身份信息(secretId, secretKey，可在腾讯云后台中的API密钥管理中查看！
        COSCredentials cred = new BasicCOSCredentials(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        //存储桶名称
        String bucketName = qiniuConfig.getBucket();
        // 指定要删除的 bucket 和路径
        cosclient.deleteObject(bucketName, key);
        // 关闭客户端(关闭后台线程)
        cosclient.shutdown();
    }

    /**
     *获取存储捅指定数量对象，最多可获取1000个
     * @param limit 同步数量
     * @param delimiter deliter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object
     * @param delimiter  prefix 文件名前缀
     * @param qiniuConfig 腾讯云配置信息
     */
    public static List<COSObjectSummary>   listObjects(int limit,String delimiter,String prefix,QiniuConfig qiniuConfig) {
        // 1 初始化用户身份信息(secretId, secretKey，可在腾讯云后台中的API密钥管理中查看！
        COSCredentials cred = new BasicCOSCredentials(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // 存储捅bucket名称, 需包含appid
        String bucketName = qiniuConfig.getBucket();

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        // 设置bucket名称
        listObjectsRequest.setBucketName(bucketName);
        // prefix表示列出的object的key以prefix开始
        listObjectsRequest.setPrefix(prefix);
        // 设置最大遍历出多少个对象, 一次listobject最大支持1000
        listObjectsRequest.setMaxKeys(limit);
        listObjectsRequest.setDelimiter(delimiter);
        ObjectListing objectListing = null;
        try {
            objectListing = cosclient.listObjects(listObjectsRequest);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // common prefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径
        List<String> commonPrefixs = objectListing.getCommonPrefixes();

        // object summary表示所有列出的object列表
        List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
        cosclient.shutdown();
        return cosObjectSummaries;
    }

    /**
     * 如果要获取超过maxkey数量的object或者获取所有的object, 则需要循环调用listobject, 用上一次返回的next marker作为下一次调用的marker,
     * 直到返回的truncated为false
     * @param qiniuConfig
     */
    public static List<Map<String,Object>> listAllObjects(QiniuConfig qiniuConfig) {
        List<Map<String,Object>> listMap=new ArrayList<>();
        // 1 初始化用户身份信息(secretId, secretKey，可在腾讯云后台中的API密钥管理中查看！
        COSCredentials cred = new BasicCOSCredentials(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // 存储捅bucket名称, 需包含appid
        String bucketName = qiniuConfig.getBucket();

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        // 设置bucket名称
        listObjectsRequest.setBucketName(bucketName);
        // prefix表示列出的object的key以prefix开始
        listObjectsRequest.setPrefix("");
        // deliter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object
        listObjectsRequest.setDelimiter("");
        // 设置最大遍历出多少个对象, 一次listobject最大支持1000
        listObjectsRequest.setMaxKeys(1000);
        ObjectListing objectListing = null;
        do {
            try {
                objectListing = cosclient.listObjects(listObjectsRequest);
            } catch (CosServiceException e) {
                e.printStackTrace();
                return null;
            } catch (CosClientException e) {
                e.printStackTrace();
                return null;
            }
            // common prefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径
            List<String> commonPrefixs = objectListing.getCommonPrefixes();

            // object summary表示所有列出的object列表
            List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
            for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
                // 文件的路径key
                String key = cosObjectSummary.getKey();
                // 文件的etag
                String etag = cosObjectSummary.getETag();
                // 文件的长度
                long fileSize = cosObjectSummary.getSize();
                // 文件的存储类型
                String storageClasses = cosObjectSummary.getStorageClass();
                Map<String,Object> map=new HashMap<>();
                map.put("key",key);
                map.put("etag",etag);
                map.put("fileSize",fileSize);
                map.put("storageClasses",storageClasses);
                listMap.add(map);
            }

            String nextMarker = objectListing.getNextMarker();
            listObjectsRequest.setMarker(nextMarker);
        } while (objectListing.isTruncated());
        cosclient.shutdown();
        return listMap;
    }

    public static void main(String[] args) {
        QiniuConfig qi=new QiniuConfig();
        qi.setAccessKey("AKIDa0BKL7bqqhJfP3gZVIq8AyVgeOWRC7t0");
        qi.setSecretKey("mHV6MLBxYAKHCnTaWN5EA5MKM3lAIDwR");
        qi.setBucket("hpapp-1301523788");
        listObjects(1000,"","",qi);
    }
}
